package math;

import java.util.ArrayList;

public class FunctionTokenizer {
	ArrayList<Token> tokens;

	public FunctionTokenizer() {
		tokens = new ArrayList<Token>();
	}

	public void tokenize(String function, double x) {
		for (int i = 0; i < function.length(); i++) {
			if (Operand.isOperand(function.charAt(i))) {
				i = getOperand(function, i);
			} else if (Operator.isOperator(function.charAt(i))) {
				i = getOperator(function, i);
			} else if (function.charAt(i) == 'X' | function.charAt(i) == 'x') {
				tokens.add(new Operand(x));
			}
		}
	}

	private int getOperator(String function, int index) {
		Operator o = new Operator(function.charAt(index));
		if (function.charAt(index) == Operator.SUB) {
			if (index == 0) {
				o.setUnary(true);
			} else if (Operator.isOperator(function.charAt(index - 1))) {
				o.setUnary(true);
			}
		}
		tokens.add(o);
		return index;
	}

	private int getOperand(String function, int index) {
		int i = index;
		char val;
		double o = 0;
		int temp;

		while (i < function.length()) {
			val = function.charAt(i);
			if (!Operand.isOperand(val)) {
				if (val == '.') {
					o = o / 10;
				} else {
					break;
				}
			} else {
				temp = Integer.parseInt(val + "");
				o = (o * 10) + temp;
			}
			i++;
		}
		tokens.add(new Operand(o));
		return i - 1;
	}

}
